package com.lagou.resume.controller;


import com.lagou.resume.entity.Resume;
import com.lagou.resume.mapper.ResumeMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/resume")
public class ResumeController {

    @Autowired
    private ResumeMapper resumeMapper;

    @RequestMapping("/queryAll")
    @ResponseBody
    public Object queryAll(Resume resume) {
        return this.resumeMapper.findAll(query(resume));
    }

    /**
     * 构造动态查询条件
     * @param resume
     * @return
     */
    Specification query(Resume resume) {
        return new Specification<Resume>() {
            @Override
            public Predicate toPredicate(Root<Resume> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList();
                if(StringUtils.isNoneBlank(resume.getName())) {
                    predicates.add(criteriaBuilder.equal(root.get("name"), resume.getName()));
                }
                if(StringUtils.isNoneBlank(resume.getPhone())) {
                    predicates.add(criteriaBuilder.equal(root.get("phone"), resume.getPhone()));
                }

                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
    }

    /**
     * 获取详情
     * @param id
     * @return
     */
    @RequestMapping("/detail")
    @ResponseBody
    Object detail(@RequestParam(required = false, defaultValue = "-1") Long id) {
        Optional val = this.resumeMapper.findById(id);
        return val.orElseGet(Resume::new);
    }

    /**
     * 保存
     * @param resume
     * @return
     */
    @RequestMapping("/doSave")
    @ResponseBody
    public Object save(Resume resume) {
        return this.resumeMapper.save(resume);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(long id) {
        this.resumeMapper.deleteById(id);
        return true;
    }

    @RequestMapping("/index")
    public String index() {
        return "/resume/resume_list";
    }
}
